package com.leo.m1802.d03;

import com.leo.common.Node;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by LEO on 2018/2/3.
 */
public class UnBlockingStack<T> {
    private AtomicReference<Node<T>> top = new AtomicReference<Node<T>>();

    public void push(T value){
        Node<T> newNode = new Node<T>(value);
        Node<T> oldTop;
        do {
            oldTop = top.get();
            newNode.next = oldTop;
        }while (!top.compareAndSet(oldTop, newNode));
    }

    public T pop(){
        Node<T> oldTop, newTop;
        do {
            oldTop = top.get();
            if (oldTop == null){   //没考虑到！
                return null;
            }
            newTop = oldTop.next;
        }while (!top.compareAndSet(oldTop, newTop));    //这个条件反了
        oldTop.next = null;         //这个考虑的不错！
        return oldTop.value;
    }
}
